import shutil
from pathlib import Path

from django.contrib.auth.models import User
from django.db import models

from system.models import Role

# def get_head_img_path(obj, file_name):
#     # 确保路径存在，如果不存在则创建
#     Path(os.path.join(settings.MEDIA_ROOT, 'img')).mkdir(parents=True, exist_ok=True)
#     return f"img/user_{obj.user_id}/{file_name}"


app_path = Path(__file__).parent

static_path = app_path / "static"


def get_head_img_path(obj, filename):
    # 拼接目录名称
    path = Path(f"{static_path}/user_{obj.user_id}/")
    # 创建目录
    path.mkdir(parents=True, exist_ok=True)

    # 删除原有的头像图片文件
    # 遍历目录中的所有文件和子目录
    for item in path.iterdir():
        try:
            # 如果是文件或链接，则删除
            if item.is_file() or item.is_symlink():
                item.unlink()
            # 如果是目录，则递归删除
            elif item.is_dir():
                shutil.rmtree(item)
        except Exception as e:
            print(f"Failed to delete {item}. Reason: {e}")

    return f"{static_path}/user_{obj.user_id}/{filename}"


class UserProfile(models.Model):
    objects: models.QuerySet

    user = models.OneToOneField(User, on_delete=models.CASCADE)  # user_id这个字段
    nick_name = models.CharField("用户昵称", max_length=24)

    head_img = models.FileField(
        "用户头像", upload_to=get_head_img_path
    )  # 上传的头像文件存放的路径

    def get_role_list(self):
        """获取角色信息"""
        role_list = Role.objects.filter(user=self.user)
        return role_list
